import { Request, Response, RequestHandler } from 'express';
import { CreditService } from '../services/CreditService';
import { asyncHandler } from '../utils/asyncHandler';

export class CreditController {
  private creditService: CreditService;

  constructor() {
    this.creditService = new CreditService();
  }

  /**
   * 获取积分包列表
   */
  getCreditPackages: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    try {
      const packages = await this.creditService.getCreditPackages();

      return res.json({
        success: true,
        data: packages,
        message: '获取积分包列表成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取积分包列表失败',
        error: error.message,
      });
    }
  });

  /**
   * 获取用户积分信息
   */
  getUserCredits: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    try {
      const creditInfo = await this.creditService.getUserCreditInfo(parseInt(userId));

      return res.json({
        success: true,
        data: creditInfo,
        message: '获取用户积分信息成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取用户积分信息失败',
        error: error.message,
      });
    }
  });

  /**
   * 使用积分
   */
  useCredits: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;
    const { credits, description, referenceId, metadata } = req.body;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    if (!credits || credits <= 0) {
      return res.status(400).json({
        success: false,
        message: '积分数量必须大于0',
      });
    }

    try {
      const creditInfo = await this.creditService.useCredits({
        userId: parseInt(userId),
        credits,
        description,
        referenceId,
        metadata,
      });

      return res.json({
        success: true,
        data: creditInfo,
        message: '积分使用成功',
      });
    } catch (error: any) {
      return res.status(400).json({
        success: false,
        message: error.message,
      });
    }
  });

  /**
   * 获取用户积分交易历史
   */
  getUserCreditTransactions: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;
    const { limit = 20, offset = 0 } = req.query;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    try {
      const transactions = await this.creditService.getUserTransactions(
        parseInt(userId),
        parseInt(limit as string),
        parseInt(offset as string)
      );

      return res.json({
        success: true,
        data: transactions,
        message: '获取积分交易历史成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '获取积分交易历史失败',
        error: error.message,
      });
    }
  });

  /**
   * 处理支付成功后的积分添加
   */
  handlePaymentSuccess: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId, packageId, paymentIntentId } = req.body;

    if (!userId || !packageId || !paymentIntentId) {
      return res.status(400).json({
        success: false,
        message: '用户ID、积分包ID和支付意图ID都是必需的',
      });
    }

    try {
      const creditInfo = await this.creditService.handlePaymentSuccess(
        parseInt(userId),
        packageId,
        paymentIntentId
      );

      return res.json({
        success: true,
        data: creditInfo,
        message: '积分添加成功',
      });
    } catch (error: any) {
      return res.status(400).json({
        success: false,
        message: error.message,
      });
    }
  });

  /**
   * 管理员：手动添加积分
   */
  addCredits: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    const { userId } = req.params;
    const { credits, validDays, description, referenceId, metadata } = req.body;

    if (!userId) {
      return res.status(400).json({
        success: false,
        message: '用户ID是必需的',
      });
    }

    if (!credits || credits <= 0) {
      return res.status(400).json({
        success: false,
        message: '积分数量必须大于0',
      });
    }

    if (!validDays || validDays <= 0) {
      return res.status(400).json({
        success: false,
        message: '有效天数必须大于0',
      });
    }

    try {
      const creditInfo = await this.creditService.addCredits({
        userId: parseInt(userId),
        credits,
        validDays,
        description,
        referenceId,
        metadata,
      });

      return res.json({
        success: true,
        data: creditInfo,
        message: '积分添加成功',
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '积分添加失败',
        error: error.message,
      });
    }
  });

  /**
   * 管理员：检查并清理过期积分
   */
  expireCredits: RequestHandler = asyncHandler(async (req: Request, res: Response) => {
    try {
      const expiredCount = await this.creditService.checkAndExpireCredits();

      return res.json({
        success: true,
        data: { expiredCount },
        message: `成功清理 ${expiredCount} 个过期积分记录`,
      });
    } catch (error: any) {
      return res.status(500).json({
        success: false,
        message: '清理过期积分失败',
        error: error.message,
      });
    }
  });
}